package com.yanftch.stopcoding.ui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class IOSSwitch extends JPanel {
    private boolean isOn = true; // 开关状态
    public interface SwitchListener {
        void switchChanged(boolean isOn);
    }

    public IOSSwitch(SwitchListener listener) {
        setPreferredSize(new Dimension(60, 30));
        setBackground(Color.LIGHT_GRAY);
        setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        // 添加鼠标点击事件
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                isOn = !isOn; // 切换状态
                repaint(); // 重新绘制
                if (listener != null) {
                    listener.switchChanged(isOn);
                }
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        // 绘制开关背景
        g.setColor(isOn ? new Color(76, 217, 100) : Color.GRAY);
        g.fillRoundRect(0, 0, getWidth(), getHeight(), 30, 30);

        // 绘制开关圆点
        g.setColor(Color.WHITE);
        int circleX = isOn ? getWidth() - 25 : 5;
        g.fillOval(circleX, 5, 20, 20);

        // 绘制开关边框
        g.setColor(Color.WHITE);
        g.drawRoundRect(0, 0, getWidth(), getHeight(), 30, 30);
    }

    public boolean isOn() {
        return isOn;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("iOS Style Switch");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new FlowLayout());
            frame.setPreferredSize(new Dimension(400, 300));

            IOSSwitch iosSwitch = new IOSSwitch(new SwitchListener() {
                @Override
                public void switchChanged(boolean isOn) {
                    System.out.println("Switch state changed: " + isOn +",     isOn="+isOn);
                }
            });
            frame.add(iosSwitch);
            frame.pack();
            frame.setVisible(true);
        });
    }
}
